package com.mjlf.akka.simple;

import akka.actor.*;
import akka.dispatch.OnSuccess;
import akka.util.Timeout;
import scala.concurrent.Future;
import scala.util.Try;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SelectionDemo
 * @auther mjlf
 * @Date 2019/8/5 10:32
 * @Description 通过路径获取actor
 */
public class SelectionDemo {

    static class SelectionActor extends AbstractActor{

        @Override
        public Receive createReceive() {
            return receiveBuilder().matchAny(msg -> {
                System.out.println("我接收到的消息是: " + msg + getSender());
            }).build();
        }
    }

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create();
        ActorRef selection1Actor = system.actorOf(Props.create(SelectionActor.class), "selection1");
        ActorRef selection2Actor = system.actorOf(Props.create(SelectionActor.class), "selection2");

        ActorSelection actorSelection = system.actorSelection("user/selection*");
//        actorSelection.tell("群发消息", ActorRef.noSender());

        Future<ActorRef> future =  actorSelection.resolveOne(new Timeout(3, TimeUnit.SECONDS));
        future.onComplete(new OnSuccess<Try<ActorRef>>() {
            @Override
            public void onSuccess(Try<ActorRef> result) throws Throwable {
                System.out.println(result.get());
            }
        }, system.dispatcher());
    }
}
